<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
	<title>Withdrawn Clients</title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <link href="./EldercareMasterPage/_finalstyle.css" rel="stylesheet" />
	<link href="./css/bootstrap.min.css" rel="stylesheet" media="screen">
    <link href="./css/bootstrap-datetimepicker.min.css" rel="stylesheet" media="screen">
	<link rel="stylesheet" type="text/css" href="./jquery/easyui.css">
	<link rel="stylesheet" type="text/css" href="./jquery/icon.css">
    <style>
        .easyui-dialog{
            height:485px!important;
        }
        .panel-window{
            height:450px!important;
        }
    </style>
</head>
<?php
    define('CONFIG_FILE',true);
    include './config.php';
    define('DB_FILE',true);
    
    session_start();
    if (empty($_SESSION["username"])||empty($_SESSION["userType"])) {
        Header("Location: ./Index.php");
        exit();
    }else{
        $userType = $_SESSION["userType"];
    }
   
    // set timeout period in seconds
    $inactive = 7200;
    // check to see if $_SESSION['timeout'] is set
    if (isset($_SESSION["timeout"])) {
        $session_life = time() - $_SESSION["timeout"];
        if ($session_life > $inactive) {
            session_destroy();
            Header("Location: Timeout.php");
        }
    }
    $_SESSION["timeout"] = time();
?>
<body>
		<div class="banner">
		</div>
		<div id="main">
			<div class="left-wrapper">
				<div class="logo">
					<img src="images/eldercare.gif" alt="logo" width="240px" />
				</div>
				<div class="menu-wrapper">
					<div id="cssmenu">
						<?php
							if ($userType == "Therapy Assistant") {
								include_once('./Sidebar/_SidebarTA.php');
							} else if ($userType == "Centre Manager") {
								include_once('./Sidebar/_SidebarCM.php');
							} else {
								include_once('./Sidebar/_SidebarSA.php');
							}
						?>
					</div>
				</div>
			</div>           
                <div id="content">
                    <div class="content2">
                        <b style="float:right; margin: 0px 0 0 0">  
							<?php
                                if (!empty($_SESSION["centreName"])) {
                                    $Username = $_SESSION["username"];
                                    $centreName = $_SESSION["centreName"];
                                    echo "Welcome, " . $Username . " ! " . $centreName . " Branch";
                                } else {
                                    $Username = $_SESSION["username"];
                                    echo "Welcome, " . $Username;
                                }
							?>
                            <input type="submit" class="btn btn-danger" value="Logout" onclick="parent.location = 'logout.php'">
						</b>
							</p>
							<br>
						<div style="float:center">
							<br>
                            <h3>Withdrawn Clients</h3>
							<br>							
							<table id="dg" title="Clients" class="easyui-datagrid" style="width:auto;height:430px; "
                                   url="CRUDWClient/get_wclients.php"
                                   toolbar="#toolbar" pagination="true"
                                   rownumbers="true" fitColumns="true" singleSelect="true">
                                <thead>
                                    <tr>
                                        <th field="NRIC" width="50" sortable="true">NRIC</th>
                                        <th field="CustomerName" width="50" sortable="true">Name</th>
                                        <th field="Citizenship" width="50"sortable="true">Citizenship</th>
                                        <th field="Daycare" width="50"sortable="true">Daycare</th>
                                        <th field="BeforeDeviation" width="50"sortable="true">Before Deviation</th>
                                        <th field="AfterDeviation" width="50"sortable="true">After Deviation</th>
                                        <th field="DateOfBirth" width="50"sortable="true">Date of Birth</th>
                                        <th field="Gender" width="50"sortable="true">Gender</th>
                                        <th field="CentreName" width="50"sortable="true">Centre Name</th>
                                    </tr>
                                </thead>
                            </table>
                            <div id="toolbar">
								<?php
    								if ($userType == "Therapy Assistant") {
    								   //echo"<a href='#' class='easyui-linkbutton' iconCls='icon-edit' plain='true' onclick='editClient()'>Edit Client</a>";					
    								}else if ($userType == "Centre Manager") {
    									echo"<a href='#' class='easyui-linkbutton' iconCls='icon-edit' plain='true' onclick='editClient()'>Edit Client</a>";
    								}else{
    									echo"<a href='#' class='easyui-linkbutton' iconCls='icon-edit' plain='true' onclick='editClient()'>Edit Client</a>
    										<a href='#' class='easyui-linkbutton' iconCls='icon-remove' plain='true' onclick='removeClient()'>Remove Client</a>";
    								}
								?>

                                <input id="searchid" name="searchid" type="text" style="border-radius:25px">
                                <a href="#" class="easyui-linkbutton" iconCls="icon-search" onClick="getClient()">Search</a>
                                <a href="#" class="easyui-linkbutton" onClick="findAll()">All</a>
                            </div>

                            <!-- Update Dialog and Form -->
                            <div>
                                <div id="updatedlg" class="easyui-dialog" style="width:400px;height:380px;padding:10px 20px"
                                     closed="true" buttons="#updatedlg-buttons">
                                    <div class="ftitle">Clients Information</div>
                                    <form id="updateform" method="post" novalidate>
                                        <div class="fitem">
                                            <label>NRIC: </label>
                                            <input id="UpdateNRIC" name="NRIC" class="easyui-validatebox" required="true" readonly = "true"style="width:155" height='auto'>
                                        </div>
                                        <div class="fitem">
                                            <label>Name: </label>
                                            <input id="UpdateCustomerName" name="CustomerName" class="easyui-validatebox" required="true"style="width:155" height='auto'>
                                        </div>
                                        <div class="fitem">
                                            <label>Citizenship: </label>
                                            <select id="UpdateCitizenship" name="Citizenship"required ="true" class="easyui-combobox"style="width:155" height='auto'>
                                                <option value="SC">Sinagapore Citizen</option>
                                                <option value="PR">Permanent Resident</option>
                                            </select>
                                        </div>
                                        <div class="fitem">
                                            <label>Daycare: </label>
                                            <select id="UpdateDaycare" name="Daycare"required ="true" class="easyui-combobox"style="width:155" height='auto'>
                                                <option value="Yes">Yes</option>
                                                <option value="No">No</option>
                                            </select>
                                        </div>
                                        <div class="fitem">
                                            <label>Before Deviation: </label>
                                            <input id="UpdateBeforeDeviation" name="BeforeDeviation" class="easyui-validatebox" required="true"style="width:155" height='auto'>
                                        </div>
                                        <div class="fitem">
                                            <label>After Deviation: </label>
                                            <input id="UpdateAfterDeviation" name="AfterDeviation" class="easyui-validatebox" required="true"style="width:155" height='auto'>
                                        </div>
                                        <div class="fitem">
                                            <label>Date of Birth: </label>
                                            <input id="UpdateDateOfBirth" name="DateOfBirth" type="date" value "" data-options="formatter:myformatter,parser:myparser" class="easyui-datebox" required="true"style="width:155" height='auto' >
                                        </div>
                                        <div class="fitem">
                                            <label>Gender: </label>
                                            <select id="UpdateGender" name="Gender"required ="true" class="easyui-combobox"style="width:155" height='auto'>
                                                <option value="M">Male</option>
                                                <option value="F">Female</option>
                                            </select>
                                        </div>
                                        <div class="fitem">
                                            <label>Centre: </label>
                                            <select id="UpdateCentreId" name="CentreId" required = "true" class="easyui-combobox"style="width:155" height='auto'>
											<option value="-1">Withdrawn</option>
											<?php
                                                require_once './Tool/DB/SqlDBManager.class.php';

                                                $sqlDBManager = new SqlDBManager();
                                                if ($userType == "System Admin"){
                                                    $sql="SELECT CentreId, CentreName FROM Centre";
                                                    $res=$sqlDBManager->queryRows($sql);
                                                }else{
                                                    $sql="SELECT CentreId, CentreName FROM Centre WHERE CentreName=?";
                                                    $parameters=array($centreName);
                                                    $res=$sqlDBManager->queryRows($sql,$parameters);
                                                }
                                                if(!empty($res)){
                                                    for($i=0;$i<count($res);$i++){
                                                        echo "<option value=\"".$res[$i]['CentreId']."\">".$res[$i]['CentreName']."</option>";          
                                                    }
                                                }
                                                //close connection
                                                $sqlDBManager->close_connect();
											?>
                                            </select>
                                        </div>
                                    </form>
                                </div>
                                <div id="updatedlg-buttons">
                                    <a href="#" class="easyui-linkbutton" iconCls="icon-ok" onclick="updateClient()">Save</a>
                                    <a href="#" class="easyui-linkbutton" iconCls="icon-cancel" onclick="javascript:$('#updatedlg').dialog('close')">Cancel</a>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="clear"></div>
                    <div><p></p></div>
                </div>
		</div>
		<div id="footer"> &copy; 2013 MP22 IIT-IT Temasek Polytechnic</div>
    </body> 
<script type="text/javascript" src="./jquery/jquery-1.6.1.min.js"></script>
<script type="text/javascript" src="./jquery/jquery-1.4.4.min.js"></script>

<script type="text/javascript" src="./jquery/jquery.easyui.min.js"></script>
<script type="text/javascript">
	function myformatter(date) {
		var y = date.getFullYear();
		var m = date.getMonth() + 1;
		var d = date.getDate();
		return y + '-' + (m < 10 ? ('0' + m) : m) + '-' + (d < 10 ? ('0' + d) : d);
	}
	function myparser(s) {
		if (!s)
			return new Date();
		var ss = (s.split('-'));
		var y = parseInt(ss[0], 10);
		var m = parseInt(ss[1], 10);
		var d = parseInt(ss[2], 10);
		if (!isNaN(y) && !isNaN(m) && !isNaN(d)) {
			return new Date(y, m - 1, d);
		} else {
			return new Date();
		}
	}
	
	function editClient() {
		$('#updatedlg').dialog('close');
		var row = $('#dg').datagrid('getSelected');
		if (row) {
			$('#updatedlg').dialog('open').dialog('setTitle', 'Edit Client');
			$('#updateform').form('load', row);
		}
	}

	function updateClient() {
		$('#updateform').form('submit', {
            onSubmit: function(){
                $(this).form('validate');
                //validate input    
                var flagNRIC=0;
                var flagCustomerName=0;
                var flagCitizenship=0;
                var flagDaycare=0;
                var flagBeforeDeviation=0;
                var flagAfterDeviation=0;
                var flagDateOfBirth=0;
                var flagGender=0;
                var flagCentreId=0;
                var flagWrongDate=0;
                $.ajax({
                    async : false,
                    type : "POST",
                    url : "./CRUDWClient/validateUpdate.php", //the page/method you wanna validate
                    data : {
                        NRIC: $("#UpdateNRIC").val(),
                        CustomerName: $("#UpdateCustomerName").val(),
                        Citizenship: $('[name="Citizenship"]').val(),
                        Daycare: $('[name="Daycare"]').val(),
                        BeforeDeviation: $("#UpdateBeforeDeviation").val(),
                        AfterDeviation: $("#UpdateAfterDeviation").val(),
                        DateOfBirth: $('[name="DateOfBirth"]').val(),
                        Gender: $('[name="Gender"]').val(),
                        CentreId: $('[name="CentreId"]').val()
                    },
                    success : function(data) {
                        var data = JSON.parse(data);
                        flagNRIC=data.flagNRIC;
                        flagCustomerName=data.flagCustomerName;
                        flagCitizenship=data.flagCitizenship;
                        flagDaycare=data.flagDaycare;
                        flagBeforeDeviation=data.flagBeforeDeviation;
                        flagAfterDeviation=data.flagAfterDeviation;
                        flagWrongDate=data.flagWrongDate;
                        flagDateOfBirth=data.flagDateOfBirth;
                        flagGender=data.flagGender;
                        flagCentreId=data.flagCentreId;
                    }
                });
                if(flagNRIC==0){
                    $.messager.show({
                        title: 'Error',
                        msg: 'Invalid Singapore NRIC Format.',
						showType:'fade',
						style:{
		                    right:'',
                    		bottom:''
		                }
                    });
                    die; 
                }else if(flagCustomerName==0){
                    $.messager.show({
                        title: 'Error',
                        msg: 'Invalid Customer Name. Customer Name cannot contain any special characters except dash and single quatation marks.',
						showType:'fade',
						style:{
		                    right:'',
                    		bottom:''
		                }
                    });
                    die; 
                }else if(flagCitizenship==0){
                    $.messager.show({
                        title: 'Error',
                        msg: 'Invalid Citizenship Type. Citizenship Type cannot contain any special characters and numbers.',
						showType:'fade',
						style:{
		                    right:'',
                    		bottom:''
		                }
                    });
                    die; 
                }else if(flagDaycare==0){
                    $.messager.show({
                        title: 'Error',
                        msg: 'Invalid Daycare Type. Daycare Type cannot contain any special characters and numbers.',
						showType:'fade',
						style:{
		                    right:'',
                    		bottom:''
		                }
                    });
                    die; 
                }else if(flagBeforeDeviation==0){
                    $.messager.show({
                        title: 'Error',
                        msg: 'Invalid Before Deviation. Before Deviation cannot contain any special characters and letters.',
						showType:'fade',
						style:{
		                    right:'',
                    		bottom:''
		                }
                    });
                    die; 
                }else if(flagAfterDeviation==0){
                    $.messager.show({
                        title: 'Error',
                        msg: 'Invalid After Deviation. After Deviation cannot contain any special characters and letters.',
						showType:'fade',
						style:{
		                    right:'',
                    		bottom:''
		                }
                    });
                    die; 
                }else if(flagWrongDate==0){
                    $.messager.show({
                        title: 'Error',
                        msg: 'The date of birth cannot be today or the future.',
						showType:'fade',
						style:{
		                    right:'',
                    		bottom:''
		                }
                    });
                    die;
                }else if(flagDateOfBirth==0){
                    $.messager.show({
                        title: 'Error',
                        msg: 'Invalid Date of Birth. Date of Birth cannot contain any letters and special characters expect dashes.',
						showType:'fade',
						style:{
		                    right:'',
                    		bottom:''
		                }
                    });
                    die; 
                }else if(flagGender==0){
                    $.messager.show({
                        title: 'Error',
                        msg: 'Invalid Gender Type. Gender Type cannot contain any special characters and numbers.',
						showType:'fade',
						style:{
		                    right:'',
                    		bottom:''
		                }
                    });
                    die; 
                }else if(flagCentreId==0){
                    $.messager.show({
                        title: 'Error',
                        msg: 'Invalid Centre Id. Centre Id cannot contain any special characters and letters.',
						showType:'fade',
						style:{
		                    right:'',
                    		bottom:''
		                }
                    });
                    die; 
                }else{
                    return $(this).form('validate');        
                }
            },
			url: './CRUDWClient/update_wclient.php',
			success: function(result) {
				var result = eval('(' + result + ')');
				if (result.success) {
					$('#updatedlg').dialog('close');		// close the dialog
					$('#dg').datagrid('reload');	// reload the user data
				} else {
					$.messager.show({
						title: 'Error',
						msg: result.msg,
                        showType:'fade',
                        style:{
                            right:'',
                            bottom:''
                        }
					});
				}
			}
		});
	}

	function removeClient() {
		var row = $('#dg').datagrid('getSelected');
		if (row) {
			$.messager.confirm('Confirm Delete Client', 'Are you sure you want to remove this client?', function(r) {
				if (r) {
                    //validate Client NRIC
                    var check = 0;
                    $.ajax({
                        async : false,
                        type : "POST",
                        url : "./CRUDWClient/validateRemove.php", //the page/method you wanna validate
                        data: {
                            NRIC: row.NRIC
                        },
                        success : function(data) {
                            check=data;
                        }
                    });
                    if(check==0){
                        $.messager.show({
                            title: 'Error',
                            msg: 'Invalid Client NRIC Format for Remove',
							showType:'fade',
							style:{
								right:'',
								bottom:''
							}
                        });
                    }else{
    					$.post('./CRUDWClient/remove_wclient.php', {NRIC: row.NRIC}, function(result) {
    						if (result.success) {
    							$('#dg').datagrid('reload');	// reload the user data
    						} else {
    							$.messager.show({// show error message
    								title: 'Error',
    								msg: result.msg,
                                    showType:'fade',
                                    style:{
                                        right:'',
                                        bottom:''
                                    }
    							});
    						}
    					}, 'json');
                    }
				}
			});
		}
	}
	function getClient() {
        //validate search input    
        var check = 0;
        $.ajax({
            async : false,
            type : "POST",
            url : "./CRUDWClient/validateSearch.php", //the page/method you wanna validate
            data: "searchid=" + $("#searchid").val(),
            success : function(data) {
                check=data;
            }
        });
        if(check==0){
            $.messager.show({
                title: 'Error',
                msg: 'Invalid Search Input. Search Input cannot contain any special characters except brackets, dashes and single quatation marks.',
				showType:'fade',
				style:{
					right:'',
					bottom:''
				}
            });
        }else{
            $('#dg').datagrid('load', {
                searchid: $('#searchid').val()
            }); 
        }
    }
	function findAll() {
		$('#dg').datagrid('load', {
		});
	}

    $(function(){ 
        $("#UpdateCitizenship").next().find("input.validatebox-text").attr("readonly","readonly");  
        $("#UpdateDaycare").next().find("input.validatebox-text").attr("readonly","readonly");
        $("#UpdateDateOfBirth").next().find("input.validatebox-text").attr("readonly","readonly");  
        $("#UpdateGender").next().find("input.validatebox-text").attr("readonly","readonly");
        $("#UpdateCentreId").next().find("input.validatebox-text").attr("readonly","readonly");       
    });
</script>	
</html>